<?php
if(!defined("YOURPHP")) exit("Access Denied");
class AttachmentAction extends AdminbaseAction {

	protected $dao;
    function _initialize()
    {	
		if($_POST['PHPSESSID'] && $_POST['userid'] && $_POST['swf_auth_key']){
			if($_POST['swf_auth_key']==md5(C('ADMIN_ACCESS').$_POST['PHPSESSID'].$_POST['userid'])){
				$_SESSION[C('USER_AUTH_KEY')] = $_POST['userid'];			
			}
			if($_POST['isadmin']) $_SESSION[C('ADMIN_AUTH_KEY')] = true;
		}
		parent::_initialize();
		$this->assign($this->siteConfig);
		$this->dao=M('Attachment');
    }
	public function index(){

		if($_SESSION[C('ADMIN_AUTH_KEY')]) $isadmin=1;
		$sessid =time();

		$types = '*.'.str_replace(",",";*.",$_REQUEST['file_types']); ;
		$this->assign('moduleid',$_REQUEST['moduleid']);
		$this->assign('file_size',$_REQUEST['file_size']);
		$this->assign('file_limit',$_REQUEST['file_limit']);
		$this->assign('file_types',$types);
		$this->assign('isthumb',$_REQUEST['isthumb']);
		$this->assign('isadmin',$isadmin);
		$this->assign('sessid',$sessid);
		$this->assign('userid',$_SESSION[C('USER_AUTH_KEY')]);
		$swf_auth_key = md5(C('ADMIN_ACCESS').$sessid.$_SESSION[C('USER_AUTH_KEY')]);
		$this->assign('swf_auth_key',$swf_auth_key);

		$this->display();
	}

	public function upload(){
		@set_time_limit(0);
		import("@.ORG.UploadFile"); 
        $upload = new UploadFile(); 
		//$upload->supportMulti = false;
        //设置上传文件大小 
        $upload->maxSize = $this->siteConfig['attach_maxsize']; 
		$upload->autoSub = true; 
		$upload->subType = 'date';
		$upload->dateFormat = 'Ym';
        //设置上传文件类型 
        $upload->allowExts = explode(',', $this->siteConfig['attach_allowext']); 
        //设置附件上传目录 
        $upload->savePath = UPLOAD_PATH; 
		 //设置上传文件规则 
        $upload->saveRule = uniqid; 

        //删除原图 
        $upload->thumbRemoveOrigin = true; 
        if (!$upload->upload()) { 
			$this->ajaxReturn(0,$upload->getErrorMsg(),0);
        } else { 
            //取得成功上传的文件信息 
            $uploadList = $upload->getUploadFileInfo(); 
			
			if($_POST['addwater']){
				import("@.ORG.Image");  
				Image::watermark($uploadList[0]['savepath'].$uploadList[0]['savename'],'',$this->siteConfig);
			}
			
			$imagearr = explode(',', 'jpg,gif,png,jpeg,bmp,ttf,tif,xls'); 
			$data=array();
			$model = M('Attachment');
			//保存当前数据对象
			$data['moduleid'] = $_REQUEST['moduleid'];
			$data['catid'] = 0;
			$data['userid'] = $_REQUEST['userid'];
			$data['filename'] = $uploadList[0]['name'];
			$data['filepath'] = $uploadList[0]['savepath'].$uploadList[0]['savename'];
			$data['filesize'] = $uploadList[0]['size']; 
			$data['fileext'] = $uploadList[0]['extension']; 
			$data['isimage'] = in_array($uploadList[0]['extension'],$imagearr) ? 1 : 0;
			$data['isthumb'] = intval($_REQUEST['isthumb']);
			$data['createtime'] = time();
			$data['uploadip'] = get_client_ip();
			$aid = $model->add($data); 
			$returndata['aid']		= $aid;
			$returndata['filepath'] = $data['filepath'];
			$returndata['fileext']  = $data['fileext'];
			$returndata['isimage']  = $data['isimage'];
			$returndata['filename'] = $data['filename'];
			$returndata['filesize'] = $data['filesize']; 


			if('1'===$_GET['mo_import']){
				if(is_file($data['filepath']) && $data['fileext']=='xls'){
					require_once 'Yourphp/Lib/Excel/reader.php';
					$exceldata = new Spreadsheet_Excel_Reader();
					$exceldata->setOutputEncoding('utf-8');
					$exceldata->read($data['filepath']);
					switch ($_GET['mo_model']){
						case 'member':
							$model=M('member');
							$newexceldata=array(
								'title'=>1,
								'addressee'=>2,
								'tel'=>3,
								'email'=>4,
								'zipcode'=>5,
								'address'=>6,
								'superintendent'=>7,
								'groupname'=>8,
								'groupid'=>9,
								'content'=>10,
							);
							break;
						case 'productadmin':
							$model=M('productadmin');
							$newexceldata=array(
								'title'=>1,
								'battery'=>2,
								'productcode'=>3,
								'brand'=>4,
								'capacity'=>5,
								'voltage'=>6,
								'color'=>7,
								'size'=>8,
								'weight'=>9,
								'dollarpreferential'=>10,
								'content'=>11,
								'dollarmarket'=>12
							);
							break;
						case 'stock':
							$model=M('stock');
							$newexceldata=array(
								'title'=>1,
								'productcode'=>2,
								'number'=>3,
								'lowernumber'=>4,
								'handling'=>5,
							);
							break;
						case 'logistics':
							$model=M('logistics');
							$newexceldata=array(
								'title'=>1,
								'addressee'=>2,
								'tel'=>3,
								'address'=>4,
								'email'=>5,
								'zipcode'=>6,
								'premium'=>7,
								'content'=>8,
							);
							break;
						case 'suppliermo':
							$model=M('suppliermo');
							$newexceldata=array(
								'title'=>1,
								'addressee'=>2,
								'tel'=>3,
								'address'=>4,
								'email'=>5,
								'zipcode'=>6,
								'content'=>7,
							);
							break;
						case 'guestdemand':
							$model=M('guestdemand');
							$newexceldata=array(
								'title'=>1,
								'tel'=>2,
								'productname'=>3,
								'productprice'=>4,
								'content'=>5,
							);
							break;
						case 'accounting':
							$model=M('accounting');
							$newexceldata=array(
								'title'=>1,
								'bigclass'=>2,
								'smallclass'=>3,
								'bank'=>4,
								'amount'=>5,
								'type'=>6,
								'content'=>7,
							);
							break;
						case 'order':
							$model=M('order');
							$newexceldata=array(
								'createtime'=>1,
								'username'=>2,
								'trackcode'=>3,
							);
							break;
						default:
							unlink($data['filepath']);
							$this->ajaxReturn($returndata,'未定义,附件已被删除.', '1');
					}
					if($_GET['mo_model']=='order'){
						for ($i = 1; $i <= $exceldata->sheets[0]['numRows']; $i++) {
							foreach($newexceldata as $kk=>$valav){
								$excel_val=$exceldata->sheets[0]['cells'][$i][$newexceldata[$kk]];
								if(!$exceldata->sheets[0]['cells'][$i][1]){break;}
								if($excel_val==''){
									$newexceldata2[$kk]=1;
									if($newexceldata[$kk]=='1'){break 2;}
								}else{
									$newexceldata2[$kk]=$excel_val;
								}
							}
							$a=strtotime(date('Y-m-d',time()-60*60*24));
							$b=$a+(60*60*24-1);
							if(isset($map)){unset($map);}
							$map['createtime'] = array(array('gt',$a),array('lt',$b)) ;
							$map['username']=$newexceldata2['username'];
							$r=$model->where($map)->find();
							if($r){
								$model->where($map)->setField('trackcode',$newexceldata2['trackcode']);
								$model->where($map)->setField('status',1);

$context=$newexceldata2['trackcode'];
$title='订单跟踪码';
if($_GET['t']){
		$this->assign ( 'content', $newexceldata2['trackcode'] );
		$etemplate='Yourphp/Tpl/Default/Public/emailtemplate/'.$_GET['t'];
		if(file_exists($etemplate)){$context=$this->fetch ($etemplate);}
}
if($_POST['tt']){$title=$_POST['tt'];}
								sendmail($r['email'],$title,$context); 
								$a.='|'.$r['email'];
							}
/*
	@$fp = fopen("test.txt","w"); 
	if(!$fp){ 
	$this->ajaxReturn($returndata, "test.txt写入失败", '1');
	exit(); 
	}else { 
	fwrite($fp,$a); 
	fclose($fp); 
	}
*/
						}
					}else{
						for ($i = 2; $i <= $exceldata->sheets[0]['numRows']; $i++) {
							foreach($newexceldata as $kk=>$valav){
								$excel_val=$exceldata->sheets[0]['cells'][$i][$newexceldata[$kk]];
								if($excel_val==''){
									$newexceldata2[$kk]=1;
									if($newexceldata[$kk]=='1'){break 2;}
								}else{
									$newexceldata2[$kk]=$excel_val;
								}
							}
							$newexceldata2['createtime'] = time();
							$newexceldata2['userid'] = $_SESSION['userid'];
							$newexceldata2['username'] = $_SESSION['username'];
							$model->data($newexceldata2)->add();
						}


					}
					unlink($data['filepath']);
					$this->ajaxReturn($returndata,'导入完成,请关闭对话框并刷新页面.', '1');
				}
				if(is_file($data['filepath']) && $_GET['mo_model']=='website' && $data['fileext']=='zip'){
					//网站语言包处理
					import("@.ORG.Phpzip");  
					$archive  = new PHPZip();
					$zipfile   = $data['filepath']; 
					$savepath  = './Yourphp/Lang';  
					$array     = $archive->GetZipInnerFilesInfo($zipfile);   
					$filecount = 0;   
					$dircount  = 0;    
					$failfiles = array();   
					for($i=0; $i<count($array); $i++) {   
						if($array[$i][folder] == 0){    
							if($archive->unZip($zipfile, $savepath, $i) > 0){       
								$filecount++;
							}else{    
								$failfiles[] = $array[$i][filename];   
							}    
						}else{         
							$dircount++;   
							if($dircount==1){$zipdirname=$array[$i][filename];}
						}  
					}
					if(count($failfiles) > 0){   
						static $failfilename;
						foreach($failfiles as $file){    
							$failfilename.='|'.$file;
						}      
					}
					$this->ajaxReturn($returndata,'解压完成.文件夹:'.$dircount.'.文件夹名称:'.$zipdirname.'. 解压文件:'.$filecount.'. 失败:'.count($failfiles).$failfilename, '1');
				}
				if(is_file($data['filepath']) && $_GET['mo_model']=='website' && $data['fileext']=='rar'){
					//网站语言包处理
					unlink($data['filepath']);
					$this->ajaxReturn($returndata,'未支持rar格式', '1');
				}
			}
			$this->ajaxReturn($returndata,L('upload_ok'), '1');
        }
	
	}

	public function filelist(){

		$where= $_REQUEST['typeid'] ?  " status=1 " : " status=0 ";
		if(!$_SESSION[C('ADMIN_AUTH_KEY')]) $where .=" and userid = ".$_SESSION['userid'] ;
		import ( '@.ORG.Page' );
		$count = $this->dao->where($where)->count();
		$page=new Page($count,12); 

		$page->urlrule = 'javascript:ajaxload('.$_REQUEST['typeid'].',{$page},\''.$_REQUEST['inputid'].'\');';
		$show = $page->show(); 
		$this->assign("page",$show);
		$list=$this->dao->order('aid desc')->where($where)
		->limit($page->firstRow.','.$page->listRows)->select();
		$this->assign('list',$list);
		$this->display();
	}



	public function showloadpage(){
		if($_SESSION[C('ADMIN_AUTH_KEY')]) $isadmin=1;
		$sessid =time();
		$types = '*.'.str_replace(",",";*.",$_REQUEST['file_types']); ;
		$this->assign('moduleid',$_REQUEST['moduleid']);
		$this->assign('file_size',$_REQUEST['file_size']);
		$this->assign('file_limit',$_REQUEST['file_limit']);
		$this->assign('file_types',$types);
		$this->assign('isthumb',$_REQUEST['isthumb']);
		$this->assign('isadmin',$isadmin);
		$this->assign('sessid',$sessid);
		$this->assign('userid',$_SESSION[C('USER_AUTH_KEY')]);
		$swf_auth_key = md5(C('ADMIN_ACCESS').$sessid.$_SESSION[C('USER_AUTH_KEY')]);
		$this->assign('swf_auth_key',$swf_auth_key);

		$this->display();
	}
	public function showloadpage1(){
		if($_SESSION[C('ADMIN_AUTH_KEY')]) $isadmin=1;
		$sessid =time();
		$types = '*.'.str_replace(",",";*.",$_REQUEST['file_types']); ;
		$this->assign('moduleid',$_REQUEST['moduleid']);
		$this->assign('file_size',$_REQUEST['file_size']);
		$this->assign('file_limit',$_REQUEST['file_limit']);
		$this->assign('file_types',$types);
		$this->assign('isthumb',$_REQUEST['isthumb']);
		$this->assign('isadmin',$isadmin);
		$this->assign('sessid',$sessid);
		$this->assign('userid',$_SESSION[C('USER_AUTH_KEY')]);
		$swf_auth_key = md5(C('ADMIN_ACCESS').$sessid.$_SESSION[C('USER_AUTH_KEY')]);
		$this->assign('swf_auth_key',$swf_auth_key);


		$type=  'html';
		$path=TMPL_PATH.$this->sysConfig['DEFAULT_THEME'].'/Public/emailtemplate/';
		$files = dir_list($path,$type);
		foreach ($files as $key=>$file){
			$filename = basename($file);
			$templates[$key]['value'] =  substr($filename,0,strrpos($filename, '.'));
			$templates[$key]['filename'] = $filename;
			$templates[$key]['filepath'] = $file;
			$templates[$key]['filesize']=byte_format(filesize($file));
			$templates[$key]['filemtime']=filemtime($file);
			$templates[$key]['ext'] = strtolower(substr($filename,strrpos($filename, '.')-strlen($filename)));
		}
		$this->assign ( 'templates',$templates );
		$this->display();
	}
}
?>